package com.helsinki.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.helsinki.pojo.Product;
import com.helsinki.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("list")
    @ResponseBody
    public PageInfo<Product> list(Model model,
                                  @RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "2") Integer pageSize) {
        return productService.queryAll(pageNum,pageSize);
    }

    @RequestMapping("findProduct")
    @ResponseBody
    public Product findById(@RequestParam String id) {
        return productService.queryByPK(id);
    }

    //保存商品
    @RequestMapping(path = "/saveProduct")
    public String save(@RequestBody Product product) throws Exception {
        String str = "";
        try {
            productService.addProduct(product);
            str = "添加成功,";
        } catch (Exception e) {
            e.printStackTrace();
            str = "添加失败！请重新添加！！！";
        }
        return "redirect:/pages/product-list.html";
    }

    @RequestMapping("/updateProduct")
    public String update(@RequestBody Product product){
        productService.updateProduct(product);
        return "redirect:/pages/product-list.html";
    }

    //删除商品
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestBody String id){
        productService.deleteProduct(id);
        return null;
    }

    @RequestMapping("/deleteSelect")
    @ResponseBody
    public String deleteSelect(@RequestBody String[] ids){
        productService.deleteSelectP(ids);
        return null;
    }

    @RequestMapping(value = "/updateStatus",method = RequestMethod.POST)
    @ResponseBody
    public String updateStatus(@RequestBody Map<String,Object> map){
        ArrayList arr = (ArrayList) map.get("ids");
        String[] ids = (String[]) arr.toArray(new String[0]);
        int status = (int) map.get("status");

        productService.updateStatus(ids,status);
        return null;
    }

}
